package com.dl7.mvp.module.video.list;

import com.dl7.mvp.api.RetrofitService;
import com.dl7.mvp.local.table.AlbumsVideoList;
import com.dl7.mvp.local.table.VideoInfo;
import com.dl7.mvp.module.base.ILoadDataView;
import com.dl7.mvp.module.base.IRxBusPresenter;
import com.dl7.mvp.rxbus.RxBus;
import com.dl7.mvp.widget.EmptyLayout;
import com.orhanobut.logger.Logger;

import java.util.List;

import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;

public class AlbumsPresenter implements IRxBusPresenter {

    final private ILoadDataView mView;
    private List<AlbumsVideoList.DataBean> mAlbumsList;
    private int mID;
    private RxBus mRxBus;

    public AlbumsPresenter(ILoadDataView view, int id, RxBus rxBus) {
        this.mView = view;
        this.mID = id;
        mRxBus = rxBus;
    }

    @Override
    public void getData() {
        Subscriber subscriber = new Subscriber<List<VideoInfo>>() {
            @Override
            public void onCompleted() {
                mView.hideLoading();
            }

            @Override
            public void onError(Throwable e) {
                Logger.e(e.toString());
                mView.showNetError(new EmptyLayout.OnRetryListener() {
                    @Override
                    public void onRetry() {
                        getData();
                    }
                });
            }

            @Override
            public void onNext(List<VideoInfo> videoList) {
                mView.loadData(videoList);
            }
        };
        RetrofitService.getAlbumsList(mID, 0, 999)
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mView.showLoading();
                    }
                })
                .compose(mView.bindToLife())
                .subscribe(subscriber);

    }

    @Override
    public void getMoreData() {
    }

    @Override
    public <T> void registerRxBus(Class<T> eventType, Action1<T> action) {
        Subscription subscription = mRxBus.doSubscribe(eventType, action, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                Logger.e(throwable.toString());
            }
        });
        mRxBus.addSubscription(this, subscription);
    }

    @Override
    public void unregisterRxBus() {
        mRxBus.unSubscribe(this);
    }
}
